package com.liufei1988.spring.overview.dependency.lookup;

import com.liufei1988.spring.overview.annotation.Super;
import com.liufei1988.spring.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

public class DenpendencyLookupDemo {
    public static void main(String[] args){
        //配置XML文件
        //启动spring应用上下文

        BeanFactory beanFactory=new ClassPathXmlApplicationContext("META-INF/dependency-lookup-context.xml");
        //按名称查找
        User user= (User) beanFactory.getBean("user");
        System.out.println(user);
        //延迟加载
        lookupInLazy(beanFactory);
        //实时查找
        lookupInRealTime(beanFactory);
        //按照类型查找、单一类型
        lookupByType(beanFactory);
        //按照类型查找结合对象
        lookupCollectionByType(beanFactory);

        // 通过注解查找对象
        lookupByAnnotationType(beanFactory);

    }

    private static void lookupInLazy(BeanFactory beanFactory){
        ObjectFactory<User> objectFactory = (ObjectFactory<User>) beanFactory.getBean("objectFactory");
        User user = objectFactory.getObject();
        System.out.println("延迟查找：" + user);
    }
    
    public static void lookupInRealTime(BeanFactory beanFactory){
        User user=(User) beanFactory.getBean("user");
        System.out.println("实时查找："+user);
    }
    private static void lookupByType(BeanFactory beanFactory){
        User user=beanFactory.getBean(User.class);
        System.out.println("按照类型查找："+user);
    }

    private static void lookupCollectionByType(BeanFactory beanFactory){
        if (beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory=(ListableBeanFactory)beanFactory;
            Map<String,User> users=listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到的所有的User集合对象: "+users);
        }
    }

    private static void lookupByAnnotationType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = (Map) listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println("查找标注 @Super 所有的 User 集合对象：" + users);
        }
    }
}
